<?php

class AdminController extends Zend_Controller_Action {
	/**
	 * @var Zend_Auth
	 */
	protected $auth = null;
	
	/**
	 * @var Zend_Log
	 */
	protected $logger = null;
	
	public function init() {
		$this->logger = new Zend_Log ();
		$this->logger->addWriter ( new Zend_Log_Writer_Firebug () );
		require_once 'Artdepot/Auth/Admin.php';
		$this->auth = Artdepot_Auth_Admin::getInstance ();
		Zend_Layout::getMvcInstance ()->setLayout ( "admin.layout" );
		$this->view->adminMenuClass = array ();
		
		if (! $this->auth->getIdentity () && $this->_request->getActionName () != "login") {
			$this->_redirect ( "/admin/login" );
		} else {
			$this->view->currentAdmin = $this->auth->getIdentity ();
		}
	}
	
	public function setCurrentMenu($action) {
		$this->view->adminMenuClass ["$action"] = 'class="current"';
	}
	
	public function indexAction() {
		$this->_forward ( "manage-artwork" );
	}
	
	public function addArtistAction() {
		$this->setCurrentMenu ( "manage-artist" );
		$form = new Form_Artist ();
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Artist ();
				$table->insert ( $values );
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-artist" );
			}
		}
		
		$form->setAction ( "/admin/add-artist" )->setMethod ( "POST" );
		$this->view->form = $form;
	}
	
	public function editArtistAction() {
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-artist" );
		} else {
			$artistId = ( int ) $this->_request->getParam ( "id" );
		}
		$this->setCurrentMenu ( "manage-artist" );
		$form = new Form_Artist ();
		$form->setAction ( "/admin/edit-artist/id/$artistId" )->setMethod ( "POST" );
		$form->getElement ( "photo" )->setRequired ( false );
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Artist ();
				$artist = $table->fetchRow ( "id = $artistId" );
				if (! $artist) {
					throw new Zend_Exception ( "指定的艺术家不存在" );
				}
				if ($values ["photo"] == null) {
					unset ( $values ["photo"] );
				}
				$table->update ( $values, "id=$artistId" );
				$this->_redirect ( "/admin/manage-artist" );
			} else {
				$this->logger->debug ( "No" );
				$this->logger->debug ( $values );
			}
		} else {
			$table = new Model_DbTable_Artist ();
			$artist = $table->fetchRow ( "id = $artistId" );
			if ($artist) {
				$form->setDefaults ( $artist->toArray () );
			} else {
				throw new Zend_Exception ( "指定的艺术家不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function manageArtistAction() {
		$this->view->title = "艺术家管理";
		$this->setCurrentMenu ( "manage-artist" );
		$table = new Model_DbTable_Artist ();
		$this->view->artists = $table->fetchAll ();
	}
	
	public function manageArtworkAction() {
		$this->setCurrentMenu ( "manage-artwork" );
		$table = new Model_DbTable_ArtWork ();
		$this->view->artworks = $table->fetchAll ( null, "artist ASC" );
	}
	
	public function manageNewsAction() {
		$this->setCurrentMenu ( "manage-news" );
		$table = new Model_DbTable_News ();
		$this->view->news = $table->fetchAll ();
	}
	
	public function manageExhibitionAction() {
		$this->setCurrentMenu ( "manage-exhibition" );
		$table = new Model_DbTable_Exhibition ();
		$this->view->exhibitions = $table->fetchAll ();
	}
	
	public function manageCustomerAction() {
		$this->setCurrentMenu ( "manage-customer" );
		$this->view->title = "客户管理";
		
		$table = new Model_DbTable_Customer ();
		$this->view->customers = $table->fetchAll ( null, "register_on DESC" );
	}
	
	public function manageReviewerAction() {
		$this->setCurrentMenu ( "manage-reviewer" );
		$this->view->title = "批评家管理";
		$table = new Model_DbTable_Reviewer ();
		$this->view->reviewers = $table->fetchAll ();
	}
	
	public function manageOrderAction() {
		$this->setCurrentMenu ( "manage-order" );
		$this->view->title = "订单管理";
		$table = new Model_DbTable_Order ();
		$orders = $table->fetchAll ( null, "status ASC" );
		$this->view->orders = $orders;
	}
	
	public function addArtworkAction() {
		$this->view->title = "艺术品管理";
		$this->setCurrentMenu ( "manage-artwork" );
		
		$form = new Form_ArtWork ();
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_ArtWork ();
				
				//				$rmb = $values["rmb_price"];
				//				$usd = ceil($rmb / 6);
				//				$uro = ceil($rmb / 7);
				//				
				//				$usd = ceil($rmb / 6) % 10 ? ((ceil($usd/10 + 10)) * 10) : $usd;
				//				$uro = ceil($rmb / 7) % 10 ? ((ceil($uro/10 + 10)) * 10) : $uro;
				//				
				//				
				//				$values["usd_price"] = $usd;
				//				$values["uro_price"] = $uro;
				$values ["tags"] = is_array ( $values ["tags"] ) ? implode ( ",", $values ["tags"] ) : $values ["tags"];
				$values ["style"] = is_array ( $values ["style"] ) ? implode ( ",", $values ["style"] ) : $values ["style"];
				$values ["subject"] = is_array ( $values ["subject"] ) ? implode ( ",", $values ["subject"] ) : $values ["subject"];
				$values ["relational_works"] = is_array ( $values ["relational_works"] ) ? implode ( ",", $values ["relational_works"] ) : $values ["relational_works"];
				
				$matches = array();
    			if(preg_match('/^(\d+(?:\.\d)?)\s*x\s*(\d+(?:\.\d)?)(?:\s*cm)?(?:\s*x\s*(\d+(?:\.\d)?)(?:\s*cm))?$/', $values["size"], $matches)){
					$newValue = $matches[1] . " x " . $matches[2] . ($matches[3] ? (" x " .$matches[3] . " cm") : " cm");
					$inchValue = round($matches[1] * 0.3937, 1) . " x " . round($matches[2] * 0.3937, 1) 
										. ($matches[3] ? (" x " .round($matches[3] * 0.3937, 1) . " in") : " in");
					
					$values["size"] = $newValue;
					$values["inch_size"] = $inchValue;
    			}else{
    				$values["inch_size"] = "";
    			}
				
				$table->insert ( $values );
				//				$this->logger->debug("Yes");
				$this->logger->debug ( $form->getValues () );
				$this->_redirect ( "/admin/manage-artwork" );
			}
		}
		
		$form->setAction ( "/admin/add-artwork" )->setMethod ( "POST" );
		$form->getElement ( "artist" )->setAttrib ( "onchange", "getRelationalArtworks();" );
		$this->view->form = $form;
	}
	
	public function editArtworkAction() {
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-artwork" );
		} else {
			$artworkId = ( int ) $this->_request->getParam ( "id" );
		}
		$this->setCurrentMenu ( "manage-artwork" );
		$form = new Form_ArtWork ();
		$form->setAction ( "/admin/edit-artwork/id/$artworkId" )->setMethod ( "POST" );
		$form->getElement ( "photo" )->setRequired ( false );
		$form->getElement ( "artist" )->setAttrib ( "onchange", "getRelationalArtworks();" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_ArtWork ();
				$artwork = $table->fetchRow ( "id = $artworkId" );
				if (! $artwork) {
					throw new Zend_Exception ( "指定的艺术品不存在" );
				}
				if ($values ["photo"] == null) {
					unset ( $values ["photo"] );
				}
				
				//				$rmb = $values["rmb_price"];
				//				$usd = ceil($rmb / 6);
				//				$uro = ceil($rmb / 7);
				//				
				//				$usd = ceil($rmb / 6) % 10 ? ((ceil($usd/10 + 10)) * 10) : $usd;
				//				$uro = ceil($rmb / 7) % 10 ? ((ceil($uro/10 + 10)) * 10) : $uro;
				//				
				//				
				//				$values["usd_price"] = $usd;
				//				$values["uro_price"] = $uro;
				$values ["tags"] = is_array ( $values ["tags"] ) ? implode ( ",", $values ["tags"] ) : $values ["tags"];
				$values ["style"] = is_array ( $values ["style"] ) ? implode ( ",", $values ["style"] ) : $values ["style"];
				$values ["subject"] = is_array ( $values ["subject"] ) ? implode ( ",", $values ["subject"] ) : $values ["subject"];
				$values ["relational_works"] = is_array ( $values ["relational_works"] ) ? implode ( ",", $values ["relational_works"] ) : $values ["relational_works"];
				
				$matches = array();
    			if(preg_match('/^(\d+(?:\.\d)?)\s*x\s*(\d+(?:\.\d)?)(?:\s*cm)?(?:\s*x\s*(\d+(?:\.\d)?)(?:\s*cm))?$/', $values["size"], $matches)){
					$newValue = $matches[1] . " x " . $matches[2] . ($matches[3] ? (" x " .$matches[3] . " cm") : " cm");
					$inchValue = round($matches[1] * 0.3937, 1) . " x " . round($matches[2] * 0.3937, 1) 
										. ($matches[3] ? (" x " .round($matches[3] * 0.3937, 1) . " in") : " in");
					$values["size"] = $newValue;
					$values["inch_size"] = $inchValue;
    			}else{
    				$values["inch_size"] = "";
    			}
				
				$table->update ( $values, "id=$artworkId" );
				$this->_redirect ( "/admin/manage-artwork" );
			} else {
				//				$this->logger->debug ( "No" );
			//				$this->logger->debug ( $values );
			}
		} else {
			$table = new Model_DbTable_ArtWork ();
			$artwork = $table->fetchRow ( "id = $artworkId" );
			if ($artwork) {
				
				$values = $artwork->toArray ();
				$values ["tags"] = explode ( ",", $values ["tags"] );
				$values ["style"] = explode ( ",", $values ["style"] );
				$values ["subject"] = explode ( ",", $values ["subject"] );
				$values ["relational_works"] = explode ( ",", $values ["relational_works"] );
				
				$form->setDefaults ( $values );
			} else {
				throw new Zend_Exception ( "指定的艺术品不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function editExhibitionAction() {
		$this->setCurrentMenu ( "manage-exhibition" );
		$form = new Form_Exhibition ();
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-exhibition" );
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
		}
		
		$form->setAction ( "/admin/edit-exhibition" )->setMethod ( "POST" );
		$form->getElement("homepage_cover")->setRequired(false);
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Exhibition ();
				$exhibition = $table->fetchRow ( "id = id" );
				if (! $exhibition) {
					throw new Zend_Exception ( "指定的展览不存在" );
				}
				
				if(empty($values["homepage_cover"])){
					unset($values["homepage_cover"]);
				}
				
				
				
				$table->update ( $values, "id=$id" );
				//$this->_redirect ( "/admin/manage-exhibition" );
			} else {
				$this->logger->debug ( "No" );
			}
		} else {
			$table = new Model_DbTable_Exhibition ();
			$exhibition = $table->fetchRow ( "id = $id" );
			if ($exhibition) {
				$form->setDefaults ( $exhibition->toArray () );
			} else {
				throw new Zend_Exception ( "指定的展览不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function addExhibitionAction() {
		$this->setCurrentMenu ( "manage-exhibition" );
		$form = new Form_Exhibition ();
		$form->setAction ( "/admin/add-exhibition" )->setMethod ( "POST" );
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Exhibition ();
				
				$table->insert ( $values );
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-exhibition" );
			}
		}
		$this->view->form = $form;
	}
	
	public function addNewsAction() {
		$this->setCurrentMenu ( "manage-news" );
		$form = new Form_News ();
		$form->setAction ( "/admin/add-news" )->setMethod ( "POST" );
		$form->getElement ( "author" )->setValue ( $this->auth->getIdentity ()->id );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_News ();
				$table->insert ( $values );
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-news" );
			}
		}
		
		$this->view->form = $form;
	}
	
	public function editNewsAction() {
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-news" );
		} else {
			$newsId = ( int ) $this->_request->getParam ( "id" );
		}
		
		$this->setCurrentMenu ( "manage-news" );
		$form = new Form_News ();
		$form->setAction ( "/admin/edit-news" )->setMethod ( "POST" );
		$form->getElement ( "author" )->setValue ( $this->auth->getIdentity ()->id );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_News ();
				$news = $table->fetchRow ( "id = $newsId" );
				if (! $news) {
					throw new Zend_Exception ( "指定的新闻不存在" );
				}
				
				$table->update ( $values, "id=$newsId" );
				$this->_redirect ( "/admin/manage-news" );
			} else {
				$this->logger->debug ( "No" );
			}
		} else {
			$table = new Model_DbTable_News ();
			$news = $table->fetchRow ( "id = $newsId" );
			if ($news) {
				$form->setDefaults ( $news->toArray () );
			} else {
				throw new Zend_Exception ( "指定的新闻不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function editReviewerAction() {
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-reviewer" );
		} else {
			$reviewerId = ( int ) $this->_request->getParam ( "id" );
		}
		
		$this->setCurrentMenu ( "manage-reviewer" );
		$form = new Form_Reviewer ();
		$form->setAction ( "/admin/edit-reviewer" )->setMethod ( "POST" );
		
		$form->getElement ( "photo" )->setRequired ( false );
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Reviewer ();
				$reviewer = $table->fetchRow ( "id = $reviewerId" );
				if (! $reviewer) {
					throw new Zend_Exception ( "指定的批评家不存在" );
				}
				if ($values ["photo"] == null) {
					unset ( $values ["photo"] );
				}
				$table->update ( $values, "id=$reviewerId" );
				$this->_redirect ( "/admin/manage-reviewer" );
			} else {
				$this->logger->debug ( "No" );
				$this->logger->debug ( $values );
			}
		} else {
			$table = new Model_DbTable_Reviewer ();
			$reviewer = $table->fetchRow ( "id = $reviewerId" );
			if ($reviewer) {
				$form->setDefaults ( $reviewer->toArray () );
			} else {
				throw new Zend_Exception ( "指定的批评家不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function addReviewerAction() {
		$this->setCurrentMenu ( "manage-reviewer" );
		$form = new Form_Reviewer ();
		$form->setAction ( "/admin/add-reviewer" )->setMethod ( "POST" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Reviewer ();
				$table->insert ( $values );
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-reviewer" );
			}
		}
		$this->view->form = $form;
	}
	
	public function editOrderAction() {
		$this->setCurrentMenu ( "manage-order" );
		$form = new Form_Order ();
		$form->setAction ( "/admin/edit-order" )->setMethod ( "POST" );
		$form->getElement ( "artwork_id" )->setLabel ( "" );
		$form->getElement ( "customer_id" )->setLabel ( "" );
		$form->getElement ( "currency" )->setAttrib ( "onchange", "changePrice();" );
		
		$id = ( int ) $this->_request->getParam ( "id" );
		$table = new Model_DbTable_Order ();
		$theOrder = $table->fetchRow ( "id = $id" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $this->_request->getParams () )) {
				$values = $form->getValues ();
				$values ["updated_on"] = date ( "Y-m-d H:i:s" );
				
				$preStatus = $theOrder->status;
				$currentStatus = $values ["status"];
				
				$theOrder->setFromArray ( $values )->save ();
				if ($preStatus == "pending" && $currentStatus == "accepted") {
					$this->sendPayEmail ( $theOrder );
				} elseif ($preStatus != "delivering" && $currentStatus == "delivering") {
					$this->sendDeliveryEmail ( $theOrder );
				} elseif ($preStatus != "paid" && $currentStatus == "paid") {
					$theArtwork = $theOrder->getArtwork ();
					$theArtwork->knockdown_price = $theOrder->price;
					$theArtwork->knockdown_currency = $theOrder->currency;
					$this->logger->debug ( $theArtwork->toArray () );
					$theArtwork->save ();
				}
				
				$this->_redirect ( "/admin/manage-order/" );
			}
		} else {
			$form->setDefaults ( $theOrder->toArray () );
		}
		
		$this->view->order = $theOrder;
		
		$this->view->form = $form;
	}
	
	public function editCustomerAction() {
		$this->setCurrentMenu ( "manage-customer" );
		$id = ( int ) $this->_request->getParam ( "id" );
		if ($id <= 0) {
			throw new Zend_Exception ( "请指定客户ID" );
		}
		
		$form = new Form_Customer ();
		$form->setAction ( "/admin/edit-customer" )->setMethod ( "POST" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Customer ();
				$theCustomer = $table->fetchRow ( "id = $id" );
				if (! $theCustomer) {
					throw new Zend_Exception ( "指定的客户不存在" );
				}
				
				$table->update ( $values, "id=$id" );
				$this->_redirect ( "/admin/manage-customer" );
			} else {
				//$this->logger->debug ( "No" );
			}
		} else {
			$table = new Model_DbTable_Customer ();
			$theCustomer = $table->fetchRow ( "id = $id" );
			if ($theCustomer) {
				$form->setDefaults ( $theCustomer->toArray () );
			} else {
				throw new Zend_Exception ( "指定的客户不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function addOrderAction() {
		$this->setCurrentMenu ( "manage-order" );
		$form = new Form_Order ();
		$form->setAction ( "/admin/add-artwork" )->setMethod ( "POST" );
		$this->view->form = $form;
	}
	
	public function loginAction() {
		if ($this->auth->getIdentity ()) {
			$this->_redirect ( "/admin/" );
		} else {
			Zend_Layout::getMvcInstance()->disableLayout();
			$loginForm = new Form_AdminLogin ();
			
			if ($this->_request->isPost ()) {
				if ($loginForm->isValid ( $_POST )) {
					$adapter = new Zend_Auth_Adapter_DbTable ( Zend_Db_Table::getDefaultAdapter (), 'user', 'name', 'passwd', 'MD5(?)' );
					
					$adapter->setIdentity ( $loginForm->getValue ( 'name' ) );
					
					$adapter->setCredential ( $loginForm->getValue ( 'passwd' ) );
					
					$result = $this->auth->authenticate ( $adapter );
					if ($result->isValid ()) {
						$theUser = $adapter->getResultRowObject ( null, "passwd" );
						
						$this->auth->getStorage ()->write ( $theUser );
						
						//use for ckfinder to browse images on server
						$_SESSION ["ckfinder"] = true;
						
						$this->view->message = '登录成功';
						
						$this->_redirect ( '/admin/' );
						
						return;
					
					} else {
						
						$this->view->message = '用户名或者密码错误！';
					
					}
				
				} else {
					
					$this->view->message = '请填写用户名和密码！';
				
				}
			
			}
			
			$this->view->form = $loginForm;
		}
	}
	
	public function logoutAction() {
		$this->auth->clearIdentity ();
		$this->_redirect ( "/admin/" );
	}
	
	public function testAction() {
		$form = new Form_Categories ();
		$this->view->form = $form;
	}
	
	public function deleteArtistAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$artistId = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_Artist ();
			$artist = $table->fetchRow ( "id = $artistId" );
			if ($artist) {
				$artist->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-artist" );
	}
	
	public function deleteArtworkAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$artworkId = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_ArtWork ();
			$artwork = $table->fetchRow ( "id = $artworkId" );
			if ($artwork) {
				$artwork->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-artwork" );
	}
	
	public function manageArtworkCategoryAction() {
		$form = new Form_Categories ();
		$form->setAction ( "/admin/save-artwork-category" );
		$form->setMethod ( "POST" );
		
		$table = new Model_DbTable_ArtworkCategory ();
		$this->view->levelOneCategories = $table->fetchAll ( "parent = 0" );
		$this->view->levelTwoCategories = $table->fetchAll ( "parent != 0" );
		
		$this->view->form = $form;
	}
	
	public function manageArtworkStyleAction() {
		$form = new Form_Styles ();
		$form->setAction ( "/admin/save-artwork-style" );
		$form->setMethod ( "POST" );
		
		$table = new Model_DbTable_Styles ();
		$this->view->styles = $table->fetchAll ();
		
		$this->view->form = $form;
	}
	
	public function manageArtworkTagAction() {
		$form = new Form_Tags ();
		$form->setAction ( "/admin/save-artwork-tag" );
		$form->setMethod ( "POST" );
		
		$table = new Model_DbTable_Tags ();
		$this->view->tags = $table->fetchAll ();
		
		$this->view->form = $form;
	}
	
	public function saveArtworkTagAction() {
		$form = new Form_Tags ();
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Tags ();
				$tag = $table->createRow ( $values );
				if ($tag->id > 0) {
					$table->update ( $tag->toArray (), "id = $tag->id" );
				} else {
					$table->insert ( $tag->toArray () );
				}
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-artwork-tag" );
			}
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
			if ($id) {
				$table = new Model_DbTable_Tags ();
				$tag = $table->fetchRow ( "id = $id" );
				$form->setDefaults ( $tag->toArray () );
			}
		}
		$form->setAction ( "/admin/save-artwork-tag" );
		$form->setMethod ( "POST" );
		$this->view->form = $form;
	}
	
	public function deleteArtworkTagAction() {
		$id = ( int ) $this->_request->getParam ( "id" );
		if ($id > 0) {
			$table = new Model_DbTable_Tags ();
			$table->delete ( "id = $id" );
		}
		$this->_redirect ( "/admin/manage-artwork-tag" );
	}
	
	public function manageArtworkSubjectAction() {
		$form = new Form_Subjects ();
		$form->setAction ( "/admin/save-artwork-subject" );
		$form->setMethod ( "POST" );
		
		$table = new Model_DbTable_Subject ();
		$this->view->subjects = $table->fetchAll ();
		
		$this->view->form = $form;
	}
	
	public function deleteArtworkSubjectAction() {
		$id = ( int ) $this->_request->getParam ( "id" );
		if ($id > 0) {
			$table = new Model_DbTable_Subject ();
			$table->delete ( "id = $id" );
		}
		$this->_redirect ( "/admin/manage-artwork-subject" );
	}
	
	public function deleteArtworkStyleAction() {
		$id = ( int ) $this->_request->getParam ( "id" );
		if ($id > 0) {
			$table = new Model_DbTable_Styles ();
			$table->delete ( "id = $id" );
		}
		$this->_redirect ( "/admin/manage-artwork-style" );
	}
	
	public function saveArtworkStyleAction() {
		$form = new Form_Styles ();
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Styles ();
				$style = $table->createRow ( $values );
				if ($style->id > 0) {
					$table->update ( $style->toArray (), "id = $style->id" );
				} else {
					$table->insert ( $style->toArray () );
				}
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-artwork-style" );
			}
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
			if ($id) {
				$table = new Model_DbTable_Styles ();
				$style = $table->fetchRow ( "id = $id" );
				$form->setDefaults ( $style->toArray () );
			}
		}
		$form->setAction ( "/admin/save-artwork-style" );
		$form->setMethod ( "POST" );
		$this->view->form = $form;
	}
	
	public function deleteArtworkCategoryAction() {
		$id = ( int ) $this->_request->getParam ( "id" );
		if ($id > 0) {
			$table = new Model_DbTable_ArtworkCategory ();
			$table->delete ( "id = $id" );
		}
		$this->_redirect ( "/admin/manage-artwork-category" );
	}
	
	public function saveArtworkCategoryAction() {
		$form = new Form_Categories ();
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_ArtworkCategory ();
				$category = $table->createRow ( $values );
				if ($category->id > 0) {
					$table->update ( $category->toArray (), "id = $category->id" );
				} else {
					$table->insert ( $category->toArray () );
				}
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-artwork-category" );
			}
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
			if ($id) {
				$table = new Model_DbTable_ArtworkCategory ();
				$category = $table->fetchRow ( "id = $id" );
				$form->setDefaults ( $category->toArray () );
			}
		}
		$form->setAction ( "/admin/save-artwork-category" );
		$form->setMethod ( "POST" );
		$this->view->form = $form;
	}
	
	public function saveArtworkSubjectAction() {
		$form = new Form_Subjects ();
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Subject ();
				$subject = $table->createRow ( $values );
				if ($subject->id > 0) {
					$table->update ( $subject->toArray (), "id = $subject->id" );
				} else {
					$table->insert ( $subject->toArray () );
				}
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-artwork-subject" );
			}
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
			if ($id) {
				$table = new Model_DbTable_Subject ();
				$subject = $table->fetchRow ( "id = $id" );
				$form->setDefaults ( $subject->toArray () );
			}
		}
		$form->setAction ( "/admin/save-artwork-subject" );
		$form->setMethod ( "POST" );
		$this->view->form = $form;
	}
	
	public function getRelatedArtworksAction() {
		Zend_Layout::getMvcInstance ()->disableLayout ();
		$artistId = ( int ) $this->_request->getParam ( "artistId" );
		$artworkId = ( int ) $this->_request->getParam ( "artworkId" );
		if ($artistId > 0) {
			$form = new Form_RelatedArtworks ();
			$table = new Model_DbTable_ArtWork ();
			$relatedArtworks = $table->fetchAll ( "artist = $artistId" );
			$elementRelatedArtwork = $form->getElement ( "relational_works" );
			foreach ( $relatedArtworks as $relatedArtwork ) {
				/** @var $elementRelatedArtwork Zend_Form_Element_MultiCheckbox */
				$elementRelatedArtwork->addMultiOption ( $relatedArtwork->id, $relatedArtwork->name );
			}
			
			if ($artworkId > 0) {
				$theArtwork = $table->fetchRow ( "id = $artworkId" );
				if ($theArtwork) {
					$originalRelatedArtworks = explode ( ",", $theArtwork->relational_works );
					$elementRelatedArtwork->setValue ( $originalRelatedArtworks );
					$this->view->form = $elementRelatedArtwork->render ();
				}
			} else {
				$this->view->form = $elementRelatedArtwork->render ();
			}
			
		//$this->logger->debug($this->view->form);
		

		} else {
			throw new Zend_Exception ( "需要指定艺术家ID来匹配相关艺术品" );
		}
	}
	
	public function deleteReviewerAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$reviewerId = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_Reviewer ();
			$reviewer = $table->fetchRow ( "id = $reviewerId" );
			if ($reviewer) {
				$reviewer->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-reviewer" );
	}
	
	public function deleteCriticiseAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$criticiseId = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_Criticise ();
			$criticise = $table->fetchRow ( "id = $criticiseId" );
			if ($criticise) {
				$criticise->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-criticise" );
	}
	
	public function addCriticiseAction() {
		$this->setCurrentMenu ( "manage-criticise" );
		$form = new Form_Criticise ();
		$form->setAction ( "/admin/add-criticise" )->setMethod ( "POST" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Criticise ();
				$table->insert ( $values );
				//				$this->logger->debug("Yes");
				//				$this->logger->debug($form->getValues());
				$this->_redirect ( "/admin/manage-criticise" );
			}
		}
		
		$this->view->form = $form;
	}
	
	public function editCriticiseAction() {
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-criticise" );
		} else {
			$criticiseId = ( int ) $this->_request->getParam ( "id" );
		}
		
		$this->setCurrentMenu ( "manage-criticise" );
		$form = new Form_Criticise ();
		$form->setAction ( "/admin/edit-criticise" )->setMethod ( "POST" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Criticise ();
				$criticise = $table->fetchRow ( "id = $criticiseId" );
				if (! $criticise) {
					throw new Zend_Exception ( "指定的评论不存在" );
				}
				
				$table->update ( $values, "id=$criticiseId" );
				$this->_redirect ( "/admin/manage-criticise" );
			} else {
				$this->logger->debug ( "No" );
			}
		} else {
			$table = new Model_DbTable_Criticise ();
			$criticise = $table->fetchRow ( "id = $criticiseId" );
			if ($criticise) {
				$form->setDefaults ( $criticise->toArray () );
			} else {
				throw new Zend_Exception ( "指定的评论不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function manageCriticiseAction() {
		$this->setCurrentMenu ( "manage-criticise" );
		$this->view->title = "评论管理";
		$table = new Model_DbTable_Criticise ();
		$this->view->criticises = $table->fetchAll ( null, "artist DESC" );
	}
	
	public function deleteNewsAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$newsId = ( int ) $this->_request->getParam ( "id" );
			if ($newsId <= 30) {
				throw new Zend_Exception ( "该新闻是系统保留文章，请勿删除！" );
			}
			$table = new Model_DbTable_News ();
			$news = $table->fetchRow ( "id = $newsId" );
			if ($news) {
				$news->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-news" );
	}
	
	public function deleteExhibitionAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$id = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_Exhibition ();
			$item = $table->fetchRow ( "id = $id" );
			if ($item) {
				$item->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-exhibition" );
	}
	
	public function getArtworksAction() {
		Zend_Layout::getMvcInstance ()->disableLayout ();
		
		$condition = array ("category", "style", "subject", "tags", "artist" );
		$by = $this->_request->getParam ( "by" );
		$id = ( int ) $this->_request->getParam ( "id" );
		
		if (! in_array ( $by, $condition )) {
			throw new Zend_Exception ( "条件错误" );
		}
		
		if ($id <= 0) {
			throw new Zend_Exception ( "条件错误" );
		}
		
		$returns = array ();
		
		$table = new Model_DbTable_ArtWork ();
		$allRecords = $table->fetchAll ();
		
		foreach ( $allRecords as $artwork ) {
			$conditionValues = explode ( ",", $artwork->$by );
			if (in_array ( $id, $conditionValues )) {
				array_push ( $returns, $artwork );
			}
		}
		$this->view->artworks = $returns;
	}
	
	/**
	 * this is an Ajax action
	 * 
	 */
	public function getArtworksByIdsAction() {
		$postIds = $this->_request->getParam ( "ids" );
		if ($postIds == "") {
			$this->_helper->json ( array () );
		}
		//$ids = implode(",", Zend_Json::decode($postIds));
		$table = new Model_DbTable_ArtWork ();
		$records = $table->fetchAll ( "id IN ($postIds)" );
		
		$returns = array ();
		foreach ( $records as $record ) {
			array_push ( $returns, array ("id" => $record->id, "small" => $record->getPhotoWebAccessablePath ( "70x70" ), "big" => $record->getPhotoWebAccessablePath ( "260x260" ) ) );
		}
		
		$this->_helper->json ( $returns );
	}
	
	public function tabFormStyleAction() {
		Zend_Layout::getMvcInstance ()->disableLayout ();
		$form = new Form_ExhibitionTabFormStyle ();
		$form->setAction ( "/admin/get-artworks/by/style/id/" );
		$this->view->form = $form;
	}
	
	public function tabFormSubjectAction() {
		Zend_Layout::getMvcInstance ()->disableLayout ();
		$form = new Form_ExhibitionTabFormSubject ();
		$form->setAction ( "/admin/get-artworks/by/subject/id/" );
		$this->view->form = $form;
	}
	
	public function tabFormCategoryAction() {
		Zend_Layout::getMvcInstance ()->disableLayout ();
		$form = new Form_ExhibitionTabFormCategory ();
		$form->setAction ( "/admin/get-artworks/by/category/id/" );
		$this->view->form = $form;
	}
	
	public function tabFormArtistAction() {
		Zend_Layout::getMvcInstance ()->disableLayout ();
		$form = new Form_ExhibitionTabFormArtist ();
		$form->setAction ( "/admin/get-artworks/by/artist/id/" );
		$this->view->form = $form;
	}
	
	public function tabFormTagAction() {
		Zend_Layout::getMvcInstance ()->disableLayout ();
		$form = new Form_ExhibitionTabFormTag ();
		$form->setAction ( "/admin/get-artworks/by/tags/id/" );
		$this->view->form = $form;
	}
	
	public function updatePriceAction() {
		throw new Zend_Exception ( "access denied" );
		$table = new Model_DbTable_ArtWork ();
		$works = $table->fetchAll ();
		foreach ( $works as $work ) {
			$rmb = $work->rmb_price;
			$usd = ceil ( $rmb / 6 );
			$uro = ceil ( $rmb / 7 );
			
			$usd = ceil ( $rmb / 6 ) % 10 ? ((ceil ( $usd / 10 + 10 )) * 10) : $usd;
			$uro = ceil ( $rmb / 7 ) % 10 ? ((ceil ( $uro / 10 + 10 )) * 10) : $uro;
			
			$work->usd_price = $usd;
			$work->uro_price = $uro;
			
			$work->save ();
		}
	}
	
	public function getOtherPriceAction() {
		$rmb = ( int ) $this->_request->getParam ( "price" );
		$usd = ceil ( $rmb / 6 );
		
		$uro = ceil ( $rmb / 7 );
		$uro = ceil ( $rmb / 7 ) % 10 ? ((ceil ( $uro / 10 + 10 )) * 10) : $uro;
		$return ["uro_price"] = $uro;
		$usd = ceil ( $rmb / 6 ) % 10 ? ((ceil ( $usd / 10 + 10 )) * 10) : $usd;
		$return ["usd_price"] = $usd;
		$this->_helper->json ( $return );
	}
	
	public function sendDeliveryEmail($order) {
		$customerInfo = $order->getCustomer ();
		$salesEmail = "sales@fidy.net";
		$emailTitle = "Your artwork \"" . $order->getArtwork ()->name . "\" is on the road.";
		$emailContent = <<<EOF
            	Dear {$customerInfo->name},<br/>
            		the artwork "{$order->getArtwork()->name}" you ordered is on the road. <br/>
            		Good No. : {$order->good_num}<br/>
            		Delivery company: {$order->delivery_company}<br/>
            		Delivery date: {$order->delivery_date}<br/>
            		
            		Thank you.
EOF;
		$mail = new Zend_Mail ();
		$mail->setBodyHtml ( $emailContent )->setSubject ( $emailTitle )->setFrom ( $salesEmail, "artdepot sales" )->addTo ( $customerInfo->email )->send ();
	}
	
	public function sendPayEmail($order) {
		$customerInfo = $order->getCustomer ();
		$salesEmail = "sales@fidy.net";
		$emailTitle = "Your order for artwork \"" . $order->getArtwork ()->name . "\" has been accepted";
		$emailContent = <<<EOF
            	Dear {$customerInfo->name},<br/>
            		your order for artwork "{$order->getArtwork()->name}" has been accepted. <br/>
            		Please sign in our site and pay the order:<br/>
            		<a href="http://www.fidy.net/account/my-orders" target="_blank">http://www.fidy.net/account/my-orders</a><br/>
            		
            		Thank you.
EOF;
		$mail = new Zend_Mail ();
		$mail->setBodyHtml ( $emailContent )->setSubject ( $emailTitle )->setFrom ( $salesEmail, "artdepot sales" )->addTo ( $customerInfo->email )->send ();
	}
	
	public function deleteCustomerAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$id = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_Customer ();
			$customer = $table->fetchRow ( "id = $id" );
			if ($customer) {
				$customer->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-customer" );
	}
	
	public function manageFriendLinkAction() {
		$this->setCurrentMenu ( "manage-friend-link" );
		$this->view->title = "友情链接管理";
		$table = new Model_DbTable_FriendLink();
		$this->view->links = $table->fetchAll ();
	}
	
	public function deleteFriendLinkAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$id = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_FriendLink();
			$row = $table->fetchRow ( "id = $id" );
			if ($row) {
				$row->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-ad" );
	}
	
	public function addFriendLinkAction() {
		$this->setCurrentMenu ( "manage-friend-link" );
		$this->view->title = "添加友情链接";
		$form = new Form_FriendLink();
		
		$form->setAction ( "/admin/add-friend-link" )->setMethod ( "POST" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_FriendLink ();
				$table->insert ( $values );
				$this->_redirect ( "/admin/manage-friend-link" );
			}
		}
		
		$this->view->form = $form;
	}
	
	public function editFriendLinkAction() {
		$this->setCurrentMenu ( "manage-friend-link" );
		$this->view->title = "友情链接管理";
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-friend-link" );
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
		}
		$form = new Form_FriendLink ();
		$form->setAction ( "/admin/edit-friend-link/id/$id" )->setMethod ( "POST" );
		$form->getElement ( "image" )->setRequired ( false );
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_FriendLink();
				$row = $table->fetchRow ( "id = $id" );
				if (! $row) {
					throw new Zend_Exception ( "指定的友情链接不存在" );
				}
				if ($values ["image"] == null) {
					unset ( $values ["image"] );
				}
				$table->update ( $values, "id=$id" );
				$this->_redirect ( "/admin/manage-friend-link" );
			} else {
				$this->logger->debug ( "No" );
				$this->logger->debug ( $values );
			}
		} else {
			$table = new Model_DbTable_FriendLink();
			$row = $table->fetchRow ( "id = $id" );
			if ($row) {
				$form->setDefaults ( $row->toArray () );
			} else {
				throw new Zend_Exception ( "指定的友情链接不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	public function manageAdAction() {
		$this->setCurrentMenu ( "manage-ad" );
		$this->view->title = "广告管理";
		$table = new Model_DbTable_Advertisement();
		$this->view->ads = $table->fetchAll ();
	}
	
	public function deleteAdAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$id = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_Advertisement ();
			$row = $table->fetchRow ( "id = $id" );
			if ($row) {
				$row->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-ad" );
	}
	
	public function addAdAction() {
		$this->setCurrentMenu ( "manage-ad" );
		$this->view->title = "广告管理";
		$form = new Form_Advertisement();
		
		$form->setAction ( "/admin/add-ad" )->setMethod ( "POST" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Advertisement ();
				$table->insert ( $values );
				$this->_redirect ( "/admin/manage-ad" );
			}
		}
		
		$this->view->form = $form;
		
	}
	
	public function editAdAction() {
		$this->setCurrentMenu ( "manage-ad" );
		$this->view->title = "广告管理";
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-ad" );
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
		}
		$form = new Form_Advertisement ();
		$form->setAction ( "/admin/edit-ad/id/$id" )->setMethod ( "POST" );
		$form->getElement ( "image" )->setRequired ( false );
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_Advertisement ();
				$row = $table->fetchRow ( "id = $id" );
				if (! $row) {
					throw new Zend_Exception ( "指定的广告不存在" );
				}
				if ($values ["image"] == null) {
					unset ( $values ["image"] );
				}
				$table->update ( $values, "id=$id" );
				$this->_redirect ( "/admin/manage-ad" );
			} else {
				$this->logger->debug ( "No" );
				$this->logger->debug ( $values );
			}
		} else {
			$table = new Model_DbTable_Advertisement ();
			$row = $table->fetchRow ( "id = $id" );
			if ($row) {
				$form->setDefaults ( $row->toArray () );
			} else {
				throw new Zend_Exception ( "指定的广告不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}
	
	
	//销售趋势
	
	public function manageTrendsAction() {
		$this->setCurrentMenu ( "manage-trends" );
		$this->view->title = "销售趋势";
		$table = new Model_DbTable_SalesTrends();
		$this->view->trends = $table->fetchAll ();
	}
	
	public function deleteTrendsAction() {
		if (( int ) $this->_request->getParam ( "id" )) {
			$id = ( int ) $this->_request->getParam ( "id" );
			$table = new Model_DbTable_SalesTrends();
			$row = $table->fetchRow ( "id = $id" );
			if ($row) {
				$row->delete ();
			}
		}
		
		$this->_redirect ( "/admin/manage-trends" );
	}
	
	public function addTrendsAction() {
		$this->setCurrentMenu ( "manage-trends" );
		$this->view->title = "销售趋势";
		$form = new Form_SalesTrends();
		
		$form->setAction ( "/admin/add-trends" )->setMethod ( "POST" );
		
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_SalesTrends();
				$table->insert ( $values );
				$this->_redirect ( "/admin/manage-trends" );
			}
		}
		
		$this->view->form = $form;
		
	}
	
	public function editTrendsAction() {
		$this->setCurrentMenu ( "manage-trends" );
		$this->view->title = "销售趋势";
		if (! ( int ) $this->_request->getParam ( "id" )) {
			$this->_redirect ( "/admin/manage-trends" );
		} else {
			$id = ( int ) $this->_request->getParam ( "id" );
		}
		$form = new Form_SalesTrends ();
		$form->setAction ( "/admin/edit-trends/id/$id" )->setMethod ( "POST" );
		if ($this->_request->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$values = $form->getValues ();
				$table = new Model_DbTable_SalesTrends ();
				$row = $table->fetchRow ( "id = $id" );
				if (! $row) {
					throw new Zend_Exception ( "指定的销售数据不存在" );
				}
				$table->update ( $values, "id=$id" );
				$this->_redirect ( "/admin/manage-trends" );
			} else {
				$this->logger->debug ( "No" );
				$this->logger->debug ( $values );
			}
		} else {
			$table = new Model_DbTable_SalesTrends ();
			$row = $table->fetchRow ( "id = $id" );
			if ($row) {
				$form->setDefaults ( $row->toArray () );
			} else {
				throw new Zend_Exception ( "指定的数据不存在" );
			}
		
		}
		
		$this->view->form = $form;
	}

}







